package service

import (
	"encoding/json"
	"github.com/milvus-io/milvus-sdk-go/milvus"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
)

var url2="m2.moono.vip"
var collectionName string = "nlppool"
var dimension int64 = 768
var indexFileSize int64 = 1024
var metricType int64 = int64(milvus.L2)
var nq int64 = 100
var nprobe int64 = 64
var nb int64 = 1
var topk int64 = 100
var nlist int64 = 16384


var client milvus.MilvusClient = GetClient()

//连接数据库
func GetClient() milvus.MilvusClient {
	var grpcClient milvus.Milvusclient
	client := milvus.NewMilvusClient(grpcClient.Instance)
	connectParam := milvus.ConnectParam{url2, "19530"}
	err := client.Connect(connectParam)
	if err != nil {
		println("nlpdb Connect failed")
		return nil
	}
	return client
}

//创建数据库
func CreateCollection(string2 string) string {
	newdb:=string2
	boolReply, status, err := client.HasCollection(newdb)
	if boolReply == true {
		return "err"
	}
	collectionParam := milvus.CollectionParam{newdb, 768, 1024, int64(milvus.L2)}
	status, err = client.CreateCollection(collectionParam)
	if err != nil {
		return "err"
	}
	if !status.Ok() {
		return "err"
	}
	return "success"
}
type Nlphello struct {
	Hello []float32 `json:"hello"`

}
type Nlpids struct {
	Ids []int64 `json:"Ids"`
	Distances []float64 `json:"Distances"`
}

//获取向量
func Geturlval(string2 string) []float32 {
	params := url.Values{}
	Url, err:= url.Parse("http://m2.moono.vip:8000/nlpbert")
	if (err == nil){
		params.Set("string",string2)
		//如果参数中有中文参数,这个方法会进行URLEncode
		Url.RawQuery = params.Encode()
		urlPath := Url.String()
		resp,_ := http.Get(urlPath)
		defer resp.Body.Close()
		body, _ := ioutil.ReadAll(resp.Body)
		var config Nlphello
		if err := json.Unmarshal([]byte(body), &config); err == nil {
		}
		last:=config.Hello
		return last
	}else{
       return  nil
	}
}

//插入向量到数据库
func Insert(string2 string,tab string) []int64{
	me:=Geturlval(string2)
	records := make([]milvus.Entity, nb)
	records[0].FloatData = me
	insertParam := milvus.InsertParam{collectionName, tab, records, nil}
	id_array, status, err := client.Insert(&insertParam)
	if err != nil {
		println("Insert rpc failed: " + err.Error())
		return nil
	}
	if !status.Ok() {
		println("Insert vector failed: " + status.GetMessage())
		return nil
	}
	if len(id_array) != int(nb) {
		println("ERROR: return id array is null")
	}
	println("Insert vectors success!")
	return id_array
}

//查询向量
func SearchNlp(name string,top string,tab string)  milvus.TopkQueryResult{

	me:=Geturlval(name)
	topk, _ := strconv.ParseInt(top, 10, 64)
	queryRecords := make([]milvus.Entity, 1)
	queryRecords[0].FloatData = me
	var mytab = []string{tab}
	var topkQueryResult milvus.TopkQueryResult
	extraParam := "{\"nprobe\" : 32}"
	searchParam := milvus.SearchParam{collectionName, queryRecords, topk, mytab, extraParam}
	topkQueryResult, status, err := client.Search(searchParam)
	if err != nil {
		println("Search rpc failed: " + err.Error())
	}
	if !status.Ok() {
		println("Insert vector failed: " + status.GetMessage())
	
	}
	println("Search without index results: ")
    return topkQueryResult
}

//通过id删除向量
func Nlpdelete(string2 string) string {
	id_array := make([]int64, 1)
	waitid,err := strconv.ParseInt(string2, 10, 64)
	id_array[0] = waitid
	status,err := client.DeleteEntityByID(collectionName,id_array)
	if err != nil {
		return "DeleteByID error"
	}
	if !status.Ok() {
		return "DeleteByID status check error"
	}
    return  "success"
}
//通过ids删除向量
func Nlpidsdelete(id_array []int64) string {

	status,err := client.DeleteEntityByID(collectionName,id_array)
	if err != nil {
		return "DeleteByID error"
	}
	if !status.Ok() {
		return "DeleteByID status check error"
	}
	return  "success"
}

